package cn.edu.jnu.finalproject;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;

import cn.edu.jnu.finalproject.data.DataSaver;
import cn.edu.jnu.finalproject.data.BookItem;

public class MainActivity extends AppCompatActivity {
    public static final int MENU_ID_ADD = 1;
    public static final int MENU_ID_UPDATE = 2;
    public static final int MENU_ID_DELETE = 3;
    private ArrayList<BookItem> bookItems;
    private MainActivity.MainRecycleViewAdapter mainRecycleViewAdapter;
    private Toolbar toolbar;
    private  Button addButton;
    private NavigationView mNavView;
    private DrawerLayout mDrawerLayout;

    private ActivityResultLauncher<Intent> addDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            ,result -> {
                if(result != null)
                {
                    Intent intent = result.getData();
                    if(result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS)
                    {
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        String author = bundle.getString("author");
                        String translator = bundle.getString("translator");
                        String publisher = bundle.getString("publisher");
                        int pubDate1 = bundle.getInt("pubDate1");
                        int pubDate2 = bundle.getInt("pubDate2");
                        String ISBN = bundle.getString("ISBN");
                        int position = bundle.getInt("position");
                        bookItems.add(position,new BookItem(title,author,translator,publisher,pubDate1,pubDate2,ISBN,R.drawable.book));
                        mainRecycleViewAdapter.notifyItemInserted(position);
                        new DataSaver().Save(this, bookItems);
                    }
                }
            });

    private ActivityResultLauncher<Intent> updateDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            ,result -> {
                if(result != null)
                {
                    Intent intent = result.getData();
                    if(result.getResultCode() == InputBookItemActivity.RESULT_CODE_SUCCESS)
                    {
//                        Bundle bundle = intent.getExtras();
//                        String title = bundle.getString("title");
//                        double price = bundle.getDouble("price");
//                        int position = bundle.getInt("position");
                        Bundle bundle = intent.getExtras();
                        String title = bundle.getString("title");
                        String author = bundle.getString("author");
                        String translator = bundle.getString("translator");
                        String publisher = bundle.getString("publisher");
                        int pubDate1 = bundle.getInt("pubDate1");
                        int pubDate2 = bundle.getInt("pubDate2");
                        String ISBN = bundle.getString("ISBN");
                        int position = bundle.getInt("position");
                        bookItems.get(position).setTitle(title);
                        bookItems.get(position).setAuthor(author);
                        bookItems.get(position).setTranslator(translator);
                        bookItems.get(position).setPublisher(publisher);
                        bookItems.get(position).setPubDate1(pubDate1);
                        bookItems.get(position).setPubDate2(pubDate2);
                        bookItems.get(position).setISBN(ISBN);
                        //shopItems.add(position,new ShopItem(title, price , R.drawable.xjzr));
                        new DataSaver().Save(this, bookItems);
                        mainRecycleViewAdapter.notifyItemChanged(position);
                    }
                }
            });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerViewMain = findViewById(R.id.recycleview_main);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerViewMain.setLayoutManager(linearLayoutManager);

        //添加工具栏
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        toolbar.setTitle("Title");
        toolbar.setLogo(R.mipmap.ts);
        //设置导航图标，添加菜单点击事件
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.cd);


        //设置抽屉
        mNavView = (NavigationView) findViewById(R.id.nav_view);
        mNavView.setCheckedItem(R.id.item_nav_menu_news);
        mNavView.setItemIconTintList(null);
        mNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId())
                {
                    case R.id.item_nav_menu_news:
                        Toast.makeText(MainActivity.this,"news",Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId())
                {
                    case R.id.action_search:
                        Toast.makeText(MainActivity.this,"Search",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_setting:
                        Toast.makeText(MainActivity.this,"Setting",Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            }
        });

        if(mNavView != null){
            setupDrawerContent(mNavView);
        }

        //int i = 0;
        DataSaver dataSaver = new DataSaver();
        bookItems = dataSaver.Load(this);
        //shopItems = new ArrayList<>();

        if(bookItems.size() == 0) {
            bookItems.add(new BookItem("三体", "刘慈欣", "无","重庆出版社",
                    2010,11,"149463732947",R.drawable.st));
        }
        mainRecycleViewAdapter = new MainRecycleViewAdapter(bookItems);
        recyclerViewMain.setAdapter(mainRecycleViewAdapter);

        DividerItemDecoration mDivider = new
                DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        recyclerViewMain.addItemDecoration(mDivider);

        //利用按钮实现添加数据
        addButton = findViewById(R.id.add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,InputBookItemActivity.class);
                addDataLauncher.launch(intent);
            }
        });
    }
    private void setupDrawerContent(NavigationView nav_view) {
        nav_view.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        mDrawerLayout.closeDrawers();
                        mDrawerLayout.setSelected(true);
                        return true;
                    }
                });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case MENU_ID_ADD :
                //Toast.makeText(this,"item add" + item.getOrder() + " clicked" , Toast.LENGTH_LONG)
                //       .show();
                Intent intent = new Intent(this, InputBookItemActivity.class);
                intent.putExtra("position",item.getOrder());
                addDataLauncher.launch(intent);

                break;
            case MENU_ID_UPDATE:
                //Toast.makeText(this,"item update" + item.getOrder() + "clicked" , Toast.LENGTH_LONG)
                //        .show();
                bookItems.get(item.getOrder()).setTitle("updated 6");
                mainRecycleViewAdapter.notifyItemChanged(item.getOrder());

                Intent intentUpdate = new Intent(this, InputBookItemActivity.class);
                intentUpdate.putExtra("position",item.getOrder());
                intentUpdate.putExtra("title", bookItems.get(item.getOrder()).getTitle());
                intentUpdate.putExtra("author", bookItems.get(item.getOrder()).getAuthor());
                intentUpdate.putExtra("translator", bookItems.get(item.getOrder()).getTranslator());
                intentUpdate.putExtra("publisher", bookItems.get(item.getOrder()).getPublisher());
                intentUpdate.putExtra("pubDate1", bookItems.get(item.getOrder()).getPubDate1());
                intentUpdate.putExtra("pubDate2", bookItems.get(item.getOrder()).getPubDate2());
                intentUpdate.putExtra("ISBN", bookItems.get(item.getOrder()).getISBN());
                updateDataLauncher.launch(intentUpdate);

                break;
            case MENU_ID_DELETE:
                //Toast.makeText(this,"item delete" + item.getOrder() + "clicked" , Toast.LENGTH_LONG)
                //        .show();
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setTitle(R.string.confirmation)
                        .setMessage(R.string.ask)
                        .setNegativeButton(R.string.no, (dialogInterface, i) -> {

                        })
                        .setPositiveButton(R.string.yes, (dialogInterface, i) -> {
                            bookItems.remove(item.getOrder());
                            new DataSaver().Save(MainActivity.this , bookItems);
                            mainRecycleViewAdapter.notifyItemRemoved(item.getOrder());
                        }).create();
                alertDialog.show();
                break;

        }
        return super.onContextItemSelected(item);
    }

    class MainRecycleViewAdapter extends RecyclerView.Adapter<MainRecycleViewAdapter.ViewHolder> {

        private ArrayList<BookItem> localDataSet;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final TextView textViewTitle;
            private final TextView textViewAuthor;
            private final TextView textViewPublisher;
            private final TextView textViewPubDate1;
            private final TextView textViewPubDate2;
            private final ImageView imageViewImage;


            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                imageViewImage = itemView.findViewById(R.id.imageview_item_image);
                textViewTitle =itemView.findViewById(R.id.textview_item_caption);
                textViewAuthor = itemView.findViewById(R.id.textview_item_author);
                textViewPublisher = itemView.findViewById(R.id.textview_item_publisher);
                textViewPubDate1 = itemView.findViewById(R.id.textview_item_pubDate1);
                textViewPubDate2 = itemView.findViewById(R.id.textview_item_pubDate2);
                itemView.setOnCreateContextMenuListener(this);
            }

            public ImageView getImageViewImage() {
                return imageViewImage;
            }
            public TextView getTextViewTitle() {
                return textViewTitle;
            }
            public TextView getTextViewAuthor() {return textViewAuthor;}
            public TextView getTextViewPublisher() {return textViewPublisher;}
            public TextView getTextViewPubDate1() {return textViewPubDate1;}
            public TextView getTextViewPubDate2() {return textViewPubDate2;}

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0,MENU_ID_ADD, getAdapterPosition(),"Add" + getAdapterPosition());
                contextMenu.add(0,MENU_ID_UPDATE, getAdapterPosition(),"Update" + getAdapterPosition());
                contextMenu.add(0,MENU_ID_DELETE, getAdapterPosition(),"Delete" + getAdapterPosition());

            }
        }


        public MainRecycleViewAdapter(ArrayList<BookItem> dataset) {
            localDataSet = dataset;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //Create a new view,which defines the UI of th list item;
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main,parent,false);

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MainRecycleViewAdapter.ViewHolder viewHolder, final int position) {
            //Get element from your dataset at this position and replace the
            //contents of the view with that element
            viewHolder.getTextViewTitle().setText(localDataSet.get(position).getTitle());
            viewHolder.getTextViewAuthor().setText(localDataSet.get(position).getAuthor());
            viewHolder.getTextViewPublisher().setText(localDataSet.get(position).getPublisher());
            viewHolder.getTextViewPubDate1().setText(Integer.toString(localDataSet.get(position).getPubDate1()));
            viewHolder.getTextViewPubDate2().setText(Integer.toString(localDataSet.get(position).getPubDate2()));
            viewHolder.getImageViewImage().setImageResource(bookItems.get(position).getResourceId());
        }

        @Override
        public int getItemCount() {
            return localDataSet.size();
        }
    }

    @Override
    public void setSupportActionBar(@Nullable androidx.appcompat.widget.Toolbar toolbar) {
        super.setSupportActionBar(toolbar);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }
}